// 

/**
 * 图片预览功能 - 公共函数
 * 支持动态创建模态框进行图片预览，支持键盘操作、缩放等功能
 * 调用方式：imagePreview.init() 或直接调用 imagePreview.showModal(element)
 */
var imagePreview = {
	// 当前缩放比例
	currentZoom: 1,
	// 最小缩放比例
	minZoom: 0.1,
	// 最大缩放比例
	maxZoom: 5,
	// 缩放步长
	zoomStep: 0.2,
	// 当前图片索引
	currentIndex: -1,
	// 图片列表
	imageList: [],
	
	// 图片缩放和拖拽功能
	scale: 1,
	isDragging: false,
	startX: 0,
	startY: 0,
	translateX: 0,
	translateY: 0,
	imageWidth: 0,
	imageHeight: 0,

	// 初始化函数 - 为所有包含 image-preview 类的元素绑定事件
	init: function() {
		$(document).on('click', '.image-preview', function(e) {
			e.preventDefault();
			imagePreview.buildImageList();
			imagePreview.showModal(this);
		});

		// 添加自定义样式
		imagePreview.addStyles();
	},

	// 构建图片列表（支持去重）
	buildImageList: function() {
		imagePreview.imageList = [];
		var seenItems = new Set(); // 用于去重的集合
		
		$('.image-preview').each(function(index) {
			var $this = $(this);
			var id = $this.data('id');
			var filePath = $this.data('filepath');
			
			// 创建唯一标识符：优先使用id，如果没有则使用filePath
			var uniqueKey = id || filePath;
			
			// 跳过重复项（如果已存在相同id或filePath的图片）
			if (!uniqueKey || seenItems.has(uniqueKey)) {
				return true; // continue to next
			}
			
			// 记录已处理的唯一标识符
			seenItems.add(uniqueKey);
			
			// 添加到图片列表
			imagePreview.imageList.push({
				element: this,
				id: id,
				filename: $this.data('filename') || '图片预览',
				filePath: filePath
			});
		});
	},

	// 显示图片模态框
	showModal: function(element) {
		var $element = $(element);
		var attachmentId = $element.data('id');
		var filename = $element.data('filename') || '图片预览';
		var filePath = $element.data('filepath');
		
		if (!filePath) {
			console.warn('图片路径为空');
			return;
		}

		// 找到当前图片在列表中的索引
		imagePreview.currentIndex = imagePreview.imageList.findIndex(function(item) {
			return item.element === element;
		});

		// 重置缩放
		imagePreview.currentZoom = 1;

		var modalHtml = `
			<div class="modal fade" id="imagePreviewModal" tabindex="-1" role="dialog" aria-labelledby="imagePreviewLabel">
				<div class="modal-dialog modal-xl image-preview-dialog" role="document">
					<div class="modal-content image-preview-content">
						<div class="modal-header">
							<button type="button" class="close" data-dismiss="modal" aria-label="Close">
								<span aria-hidden="true">&times;</span>
							</button>
							<h4 class="modal-title" id="imagePreviewLabel">${filename}</h4>
						</div>
						<div class="modal-body image-preview-body">
							<div class="image-preview-container" title="双击复原">
								<div class="image-preview-loading" style="display: none;">
									<i class="fa fa-spinner fa-spin fa-3x"></i>
									<p>加载中...</p>
								</div>
								<img id="previewImage" src="/profile${filePath}" alt="${filename}" class="modal-image" style="display: none;">
								<div class="image-preview-error" style="display: none;">
									<i class="fa fa-exclamation-triangle fa-3x"></i>
									<p>图片加载失败</p>
								</div>
							</div>
						</div>
						<div class="modal-footer">
							<div class="pull-left">
								<span class="image-preview-info">
									<span class="image-counter">${imagePreview.currentIndex + 1} / ${imagePreview.imageList.length}</span>
									<span class="zoom-level">100%</span>
								</span>
							</div>
							<div class="pull-right">
								<button type="button" class="btn btn-sm btn-default" id="btnZoomOut" title="缩小 (或按 -)">
									<i class="fa fa-search-minus"></i>
								</button>
								<button type="button" class="btn btn-sm btn-default" id="btnZoomReset" title="重置大小 (或按 0)">
									<i class="fa fa-compress"></i>
								</button>
								<button type="button" class="btn btn-sm btn-default" id="btnRestoreOriginal" title="恢复原位 (或按 R)">
									<i class="fa fa-home"></i>
								</button>
								<button type="button" class="btn btn-sm btn-default" id="btnZoomIn" title="放大 (或按 +)">
									<i class="fa fa-search-plus"></i>
								</button>
								<button type="button" class="btn btn-sm btn-default" id="btnPrev" title="上一张 (或按左箭头)" ${imagePreview.currentIndex <= 0 ? 'disabled' : ''}>
									<i class="fa fa-chevron-left"></i>
								</button>
								<button type="button" class="btn btn-sm btn-default" id="btnNext" title="下一张 (或按右箭头)" ${imagePreview.currentIndex >= imagePreview.imageList.length - 1 ? 'disabled' : ''}>
									<i class="fa fa-chevron-right"></i>
								</button>
								<a href="/common/download?fileName=${filePath}" class="btn btn-sm btn-primary" target="_blank" title="下载">
									<i class="fa fa-download"></i>
								</a>
								<button type="button" class="btn btn-sm btn-default" data-dismiss="modal">关闭</button>
							</div>
							<div class="clearfix"></div>
						</div>
					</div>
				</div>
			</div>
		`;
		
		// 移除已存在的模态框和遮罩层
		$('#imagePreviewModal').remove();
		$('.modal-backdrop').remove();
		$('body').removeClass('modal-open');
		$('body').append(modalHtml);
		
		// 绑定事件
		imagePreview.bindModalEvents(filePath);
		
		imagePreview.initImageZoomAndDrag();
		// 显示模态框
		$('#imagePreviewModal').modal('show');
	},
			
	initImageZoomAndDrag: function () {
		var image = document.getElementById('previewImage');
		var container = image.parentElement;
		
		if (!image) return;
		
		// 初始化图片尺寸
		image.onload = function() {
			imagePreview.imageWidth = image.naturalWidth;
			imagePreview.imageHeight = image.naturalHeight;
			imagePreview.setZoom(1);
		};
		
		if (image.complete) {
			imagePreview.imageWidth = image.naturalWidth;
			imagePreview.imageHeight = image.naturalHeight;
			imagePreview.setZoom(1);
		}
		
		// 鼠标按下
		container.addEventListener('mousedown', function(e) {
			if (e.button === 0) { // 左键
				imagePreview.isDragging = true;
				imagePreview.startX = e.clientX - imagePreview.translateX;
				imagePreview.startY = e.clientY - imagePreview.translateY;
				container.style.cursor = 'grabbing';
				image.style.cursor = 'grabbing';
				e.preventDefault();
			}
		});
		
		// 鼠标移动
		document.addEventListener('mousemove', function(e) {
			if (imagePreview.isDragging) {
				imagePreview.translateX = e.clientX - imagePreview.startX;
				imagePreview.translateY = e.clientY - imagePreview.startY;
				imagePreview.updateImageTransform();
				e.preventDefault();
			}
		});
		
		// 鼠标释放
		document.addEventListener('mouseup', function(e) {
			if (imagePreview.isDragging) {
				imagePreview.isDragging = false;
				container.style.cursor = 'grab';
				image.style.cursor = 'grab';
			}
		});
		
		// 双击重置
		container.addEventListener('dblclick', function() {
			imagePreview.setZoom(1);
			imagePreview.restoreOriginal();
		});
	},

	// 更新图片变换
	updateImageTransform: function() {
		var $image = $('#imagePreviewModal .modal-image');
		var transform = `scale(${imagePreview.currentZoom}) translate(${imagePreview.translateX}px, ${imagePreview.translateY}px)`;
		$image.css({
			'transform': transform,
			'transition': imagePreview.isDragging ? 'none' : 'transform 0.2s ease'
		});
	},

	// 绑定模态框事件
	bindModalEvents: function(filePath) {
		var $modal = $('#imagePreviewModal');
		var $image = $modal.find('.modal-image');
		var $loading = $modal.find('.image-preview-loading');
		var $error = $modal.find('.image-preview-error');

		// 图片加载事件
		$image.on('load', function() {
			$loading.hide();
			$error.hide();
			$image.show();
			imagePreview.resetZoom();
		});

		$image.on('error', function() {
			$loading.hide();
			$image.hide();
			$error.show();
		});

		// 缩放按钮事件
		$modal.find('#btnZoomIn').on('click', function() {
			imagePreview.zoomIn();
		});

		$modal.find('#btnZoomOut').on('click', function() {
			imagePreview.zoomOut();
		});

		$modal.find('#btnZoomReset').on('click', function() {
			imagePreview.resetZoom();
		});

		$modal.find('#btnRestoreOriginal').on('click', function() {
			imagePreview.restoreOriginal();
		});

		// 切换图片按钮事件
		$modal.find('#btnPrev').on('click', function() {
			imagePreview.prevImage();
		});

		$modal.find('#btnNext').on('click', function() {
			imagePreview.nextImage();
		});

		// 键盘事件
		$(document).on('keydown.imagePreview', function(e) {
			if (!$modal.is(':visible')) return;

			switch(e.keyCode) {
				case 27: // ESC
					$modal.modal('hide');
					break;
				case 37: // 左箭头
					imagePreview.prevImage();
					break;
				case 39: // 右箭头
					imagePreview.nextImage();
					break;
				case 187: // +
				case 107: // 小键盘 +
					e.preventDefault();
					imagePreview.zoomIn();
					break;
				case 189: // -
				case 109: // 小键盘 -
					e.preventDefault();
					imagePreview.zoomOut();
					break;
				case 48: // 0
					e.preventDefault();
					imagePreview.resetZoom();
					break;
				case 82: // R
					e.preventDefault();
					imagePreview.restoreOriginal();
					break;
			}
		});

		// 鼠标滚轮缩放
		$image.on('wheel', function(e) {
			e.preventDefault();
			if (e.originalEvent.deltaY < 0) {
				imagePreview.zoomIn();
			} else {
				imagePreview.zoomOut();
			}
		});

		// 模态框关闭时清理事件
		$modal.on('hidden.bs.modal', function() {
			$(document).off('keydown.imagePreview');
			$image.off('wheel');
			$image.off('load.imageSwitch');
			$image.off('error.imageSwitch');
			$(this).remove();
			// 清理可能残留的遮罩层
			$('.modal-backdrop').remove();
			$('body').removeClass('modal-open');
		});
	},

	// 放大
	zoomIn: function() {
		var newZoom = Math.min(imagePreview.currentZoom + imagePreview.zoomStep, imagePreview.maxZoom);
		imagePreview.setZoom(newZoom);
	},

	// 缩小
	zoomOut: function() {
		var newZoom = Math.max(imagePreview.currentZoom - imagePreview.zoomStep, imagePreview.minZoom);
		imagePreview.setZoom(newZoom);
	},

	// 重置缩放
	resetZoom: function() {
		imagePreview.translateX = 0;
		imagePreview.translateY = 0;
		imagePreview.setZoom(1);
	},

	// 恢复到原坐标和缩放
	restoreOriginal: function() {
		imagePreview.translateX = 0;
		imagePreview.translateY = 0;
		imagePreview.setZoom(1);
	},

	// 设置缩放
	setZoom: function(zoom) {
		imagePreview.currentZoom = zoom;
		imagePreview.updateImageTransform();

		// 更新缩放级别显示
		$('.zoom-level').text(Math.round(zoom * 100) + '%');

		// 更新缩放按钮状态
		$('#btnZoomIn').prop('disabled', zoom >= imagePreview.maxZoom);
		$('#btnZoomOut').prop('disabled', zoom <= imagePreview.minZoom);
	},

	// 上一张图片
	prevImage: function() {
		if (imagePreview.currentIndex > 0) {
			var prevItem = imagePreview.imageList[imagePreview.currentIndex - 1];
			imagePreview.switchToImage(prevItem, imagePreview.currentIndex - 1);
		}
	},

	// 下一张图片
	nextImage: function() {
		if (imagePreview.currentIndex < imagePreview.imageList.length - 1) {
			var nextItem = imagePreview.imageList[imagePreview.currentIndex + 1];
			imagePreview.switchToImage(nextItem, imagePreview.currentIndex + 1);
		}
	},

	// 切换到指定图片（不重新创建模态框）
	switchToImage: function(item, newIndex) {
		var $modal = $('#imagePreviewModal');
		if ($modal.length === 0) {
			// 如果模态框不存在，则创建新模态框
			imagePreview.showModal(item.element);
			return;
		}

		// 更新当前索引
		imagePreview.currentIndex = newIndex;

		// 重置状态
		imagePreview.translateX = 0;
		imagePreview.translateY = 0;
		imagePreview.currentZoom = 1;

		// 更新标题
		var filename = item.filename || '图片预览';
		$modal.find('#imagePreviewLabel').text(filename);

		// 更新图片
		var $image = $modal.find('.modal-image');
		var $loading = $modal.find('.image-preview-loading');
		var $error = $modal.find('.image-preview-error');

		// 显示加载状态
		$loading.show();
		$error.hide();
		$image.hide();

		// 更新图片源
		$image.attr('src', '/profile' + item.filePath);
		$image.attr('alt', filename);

		// 更新计数器
		$modal.find('.image-counter').text(`${imagePreview.currentIndex + 1} / ${imagePreview.imageList.length}`);

		// 更新按钮状态
		$modal.find('#btnPrev').prop('disabled', imagePreview.currentIndex <= 0);
		$modal.find('#btnNext').prop('disabled', imagePreview.currentIndex >= imagePreview.imageList.length - 1);

		// 更新下载链接
		$modal.find('a[target="_blank"]').attr('href', '/common/download?fileName=' + item.filePath);

		// 图片加载完成后重置缩放
		$image.off('load.imageSwitch').on('load.imageSwitch', function() {
			$loading.hide();
			$error.hide();
			$image.show();
			imagePreview.resetZoom();
		});

		$image.off('error.imageSwitch').on('error.imageSwitch', function() {
			$loading.hide();
			$image.hide();
			$error.show();
		});
	},

	// 添加自定义样式
	addStyles: function() {
		if ($('#imagePreviewStyles').length > 0) return;

		var styles = `
			<style id="imagePreviewStyles">
				.image-preview-dialog {
					width: 95%;
					height: 90vh;
					margin: 5vh auto;
				}
				.image-preview-content {
					height: 100%;
					display: flex;
					flex-direction: column;
				}
				.image-preview-body {
					flex: 1;
					padding: 0;
					overflow: hidden;
					display: flex;
					align-items: center;
					justify-content: center;
					background: #fff;
				}
				.image-preview-container {
					position: relative;
					width: 100%;
					height: 100%;
					display: flex;
					align-items: center;
					justify-content: center;
				}
				.modal-image {
					max-width: 100%;
					max-height: 100%;
					object-fit: contain;
					cursor: grab;
				}
				.modal-image:active {
					cursor: grabbing;
				}
				.image-preview-loading, .image-preview-error {
					text-align: center;
					color: #fff;
				}
				.image-preview-loading i, .image-preview-error i {
					margin-bottom: 10px;
				}
				.image-preview-info {
					line-height: 34px;
					color: #666;
				}
				.image-counter {
					margin-right: 15px;
				}
				.zoom-level {
					font-weight: bold;
				}
			</style>
		`;
		$('head').append(styles);
	}
};
